package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.domain.User;
import com.example.result.JsonResult;
import com.example.service.UserService;
import com.example.untils.MD5encrypt;
import com.example.untils.FileUntils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController  //@ResponseBody+@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
    @Autowired
    private UserService userService;
    //注册用户
    @PostMapping("/insert")
    public JsonResult insert(@RequestBody User user){
        //JsonResult<Void> result=new JsonResult<>();
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        wrapper.or();
        wrapper.eq("email",user.getEmail());
        User one = userService.getOne(wrapper);
        if(one!=null){
            throw new RuntimeException("用户或邮箱已存在");
        }
        String salt= UUID.randomUUID().toString().toUpperCase();   //随机生成盐值
        String md5Password= MD5encrypt.getMD5Password(user.getPassword(),salt);   //MD5加密
        user.setPassword(md5Password);user.setSalt(salt);

        user.setIs_delete(0);   //是否删除：0-未删除，1-已删除
        user.setCreated_user(user.getCreated_user());  //日志-创建人
        user.setModified_user(user.getCreated_user());  //日志-创建时间
        user.setCreated_time(new Date());user.setModified_time(new Date());   //日志-最后修改执行人，//日志-最后修改时间

        boolean flag = userService.save(user);
        if(!flag){
            throw new RuntimeException("用户创建异常");
        }
        return new JsonResult(flag,"用户创建成功");
    }
    //用户登录
    @PostMapping("/login")
    public JsonResult login(@RequestBody User user, HttpSession session){
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        wrapper.eq("is_delete",0);
        User result = userService.getOne(wrapper);
        if(result==null||result.getIs_delete()==1){
            throw new RuntimeException("用户不存在");
        }
        String salt=result.getSalt();
        String md5Password = MD5encrypt.getMD5Password(user.getPassword(), salt);
        if(!result.getPassword().equals(md5Password)){
            throw new RuntimeException("密码不正确");
        }
        User one=new User();
        one.setUid(result.getUid());one.setUsername(result.getUsername());one.setAvatar(result.getAvatar());
        session.setAttribute("user",one);
        return new JsonResult(true,"登录成功");
    }
    //获取session中的user
    @GetMapping("/getUser")
    public JsonResult select(HttpSession session){
        User user = getSessionUser(session);
        if(user==null){
            throw new RuntimeException("获取失败");
        }
        return new JsonResult(true,"",user);
    }
    //获取user
    @GetMapping("/selectUser")
    public JsonResult selectUser(HttpSession session){
        User one=getSessionUser(session);
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("uid",one.getUid());
        User user = userService.getOne(wrapper);
        if(user==null){
            throw new RuntimeException("用户不存在");
        }
        return new JsonResult(true,"",user);
    }
    //注销用户
    @GetMapping("/logout")
    public ModelAndView logout(HttpSession session){
        session.removeAttribute("user");
        ModelAndView model=new ModelAndView("redirect:/index.html");
        return model;
    }
    //用户密码修改
    @PutMapping("/update/{password}/{password2}")
    public JsonResult update(@PathVariable String password,@PathVariable String password2, HttpSession session){
        User one=getSessionUser(session);
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("uid",one.getUid());
        User userResult = userService.getOne(wrapper);
        //获取密码并验证
        System.out.println("当前用户"+userResult);
        String salt=userResult.getSalt();
        String md5Password = MD5encrypt.getMD5Password(password, salt);
        if(!md5Password.equals(userResult.getPassword())){
            throw new RuntimeException("原密码不正确");
        }
        //加密新密码并输入数据库
        String newSalt= UUID.randomUUID().toString().toUpperCase();   //随机生成盐值
        String newMd5Password= MD5encrypt.getMD5Password(password2,salt);   //MD5加密
        User updateUser=new User();
        updateUser.setPassword(newMd5Password);updateUser.setSalt(newSalt);

        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("uid",one.getUid());
        boolean flag = userService.update(updateUser,queryWrapper);
        if(!flag){
            throw new RuntimeException("更新失败");
        }
        return new JsonResult(flag,"更新成功");
    }
    //修改用户信息
    @PutMapping("/updateUser")
    public JsonResult updateUser(@RequestBody User user,HttpSession session){
        User one = getSessionUser(session);

        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("uid",one.getUid());
        boolean flag = userService.update(user, queryWrapper);
        if(!flag){
            throw new RuntimeException("修改失败，请重试!");
        }
        //更新sesson中的数据
        session.setAttribute("user",user);

        return new JsonResult(flag,"修改成功");
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
    @Value("${server.port}")     //获取项目启动端口
    private String port;
    //修改头像
    @PostMapping("/upload")
    public JsonResult upload(@RequestParam("file") MultipartFile upload,HttpSession session){
        // 获取编译目录下static的绝对路径
        String realPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();

        String format = sdf.format(new Date());
        String partUrl="/images/upload/"+format;
        realPath +=partUrl;
        File file=new File(realPath);
        //判断编译路径是否创建
        if (!file.isDirectory()) {
            file.mkdirs();
        }
        //获取随机的文件名
        String fullFilename = FileUntils.getUIIDFileName(upload);
        //转移上传文件到（单机）
        try {
            upload.transferTo(new File(file,fullFilename));   //将上传文件保存到编译路径
        } catch (IOException e) {
            throw new RuntimeException("上传失败");
        }

        //保存上传目录的文件到未编译路劲
        String javaPath=null;
        try {
            //ResourceUtils.getURL("").getPath()：获取项目的根目录
            javaPath= ResourceUtils.getURL("src/main/resources/static").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        javaPath+=partUrl;
        FileUntils.saveFile(realPath,javaPath,fullFilename);

        //修改数据库中的头像地址
        User user=getSessionUser(session);
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("uid",user.getUid());
        User result=new User();
        result.setAvatar("http://localhost:"+port+"/images/upload/"+format+fullFilename);  //使用本地的网络地址访问
        boolean flag = userService.update(result,wrapper);
        if(!flag){
            throw new RuntimeException("上传失败");
        }
        //更新sesson中的数据
        user.setAvatar(result.getAvatar());
        session.setAttribute("user",user);

        return new JsonResult(true,"上传成功");
    }
    //网络地址更新图片
    @PutMapping("/updateAvatar")
    public JsonResult updateAvatar(@RequestBody User user,HttpSession session){
        User one=getSessionUser(session);
        //修改数据库中的头像地址
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("uid",one.getUid());
        boolean flag = userService.update(user,wrapper);
        if(!flag){
            throw new RuntimeException("上传失败");
        }

        //更新sesson中的数据
        one.setAvatar(user.getAvatar());
        session.setAttribute("user",one);

        return new JsonResult(true,"上传成功");
    }
    //
}
